import { LoginRequest } from '@/api/system/login.request'
import { removeAccessToken, setAccessToken } from '@/utils'

/** 第一个参数是该 store 的唯一 id */
export default defineStore('user', () => {
  const tagsViewStore = useTagsViewStore()

  /** 当前用户信息 */
  const user = ref({} as UserType.Entity)
  /** 用户角色编码表 */
  const permissions = ref<string[]>([])
  /** 用户权限编码表 */
  const roles = ref<string[]>([])

  /** 登录 */
  async function login(body: UserType.LoginParams) {
    const data = await LoginRequest.login(body)
    setAccessToken(data.accessToken)
  }

  /** 获取登录账号的信息 */
  async function getInfo() {
    try {
      const data = await LoginRequest.getInfo()
      roles.value = data.roles
      permissions.value = data.permissions
      user.value = data.user
    } catch (error) {
      return Promise.reject(error)
    }
  }

  /** 退出登录 */
  async function logout() {
    await LoginRequest.logout()
    tagsViewStore.clear()
    removeAccessToken()
  }

  /** 简化数据获取 */
  const avatar = computed(() => user.value.avatar ?? new URL('../../assets/images/default/default-avatar.gif', import.meta.url).href)

  return { avatar, roles, permissions, user, login, getInfo, logout }
})
